package com.newly.gateway.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.List;

/**
 * @program: newly-parent
 * @remark:
 * @author: guan
 * @create: 2022-01-27 16:16
 */
//@Component
@Slf4j
public class TestGatewayFilterFactory extends AbstractGatewayFilterFactory<TestGatewayFilterFactory.Config> {

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("enabled");
    }

    public TestGatewayFilterFactory() {
        super(Config.class);
        log.info("Loaded TestGatewayFilterFactory");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            if (!config.isEnabled()) {
                return chain.filter(exchange);
            }

            if (null != exchange) {
                ServerHttpRequest httpRequest = exchange.getRequest();
                try {

                    Flux<DataBuffer> dataBufferFlux = httpRequest.getBody();
                    //获取body中的数据
                    String body = FilterRequestResponseUtil.resolveBodyFromRequest(dataBufferFlux);
                    log.info("body:{}",body);

                } catch (Exception e) {
                    log.error("异常:",e);
                    return chain.filter(exchange);
                }
            }
            return chain.filter(exchange);
        };
    }

    public static class Config {
        /**
         * 控制是否开启统计
         */
        private boolean enabled;

        public Config() {
        }

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }
}
